package concurrents;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 读锁和写锁分开，同样有公平和非公平之分
 * 在性能要求不同的场合使用
 * @author glogo
 *
 */
public class ReadWriteLockTest {

	private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	private static Lock readLock = readWriteLock.readLock();
	private static Lock writeLock = readWriteLock.writeLock();
	
	private int index = 0;
	
	public Object handleRead() throws InterruptedException{
		try{
			readLock.lock();
			Thread.sleep(10);
			return index;
		}finally{
			readLock.unlock();
		}
	}
	
	public void handleWrite() throws InterruptedException{
		try{
			writeLock.lock();
			Thread.sleep(10);
			index++;
		}finally{
			writeLock.unlock();
		}
	}
	
}
